<template>
  <div>
    <a-modal
      :title="title"
      :width="800"
      :visible="visible"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
      wrapClassName="ant-modal-cust-warp"
      style="top:5%;height: 85%;overflow-y: hidden"
    >
      <span slot="closeIcon">
          <a-icon type="close-circle"/>
      </span>
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务名称">{{process.modelName}}</a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="任务关键字">{{process.keyWord}}</a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="节点描述">{{description}}</a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="开始时间">{{startTime}}</a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="结束时间">{{endTime}}</a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="执行天数">{{dateDiff}}</a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="时间状态">{{timeStatus}}</a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="说明文档">
          <a-list v-if="process.attachments">
            <a-list-item
              v-for="(item,index) in process.attachments.split(',')"
              :key="'attachment-'+index"
            >
              <a :href="item" download="abc">{{item |fileName}}</a>
            </a-list-item>
          </a-list>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="开发文档" v-if="fileAttachments">
          <a-list>
            <a-list-item
              v-for="(item,index) in currentTask.attachments.split(',')"
              :key="'attachment-'+index"
            >
              <a :href="item" download="abc">{{item |fileName}}</a>
            </a-list-item>
          </a-list>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="备注">{{process.remark}}</a-form-item>
        <template v-if="opinionList && opinionList.length > 0">
          <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批过程">
            <a-list item-layout="horizontal">
              <a-list-item v-for="(item,index) in opinionList" :key="'list-item'+index">
                <span slot="actions">{{item.flag ? '通过':'回退'}}</span>
                <a-list-item-meta :description=" item.createTime">
                  <span slot="title">{{ item.opName }}</span>
                </a-list-item-meta>
                <!--              <div>{{item.opinion}}</div>-->
                <div v-if="item.opinion">任务总结提示：{{item.opinion}}</div>
              </a-list-item>
            </a-list>
          </a-form-item>
        </template>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批意见">
          <a-textarea
            :rows="5"
            placeholder="请输入审批意见"
            v-decorator="[ 'opinion', validatorRules.opinion ]"
          />
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="上传文件">
          <a-upload-dragger
            name="file"
            :multiple="true"
            :accept="outFileType"
            :action="uploadAction"
            :fileList="fileList"
            :before-upload="beforeUpload"
            @change="uploadChanged"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox"/>
            </p>
            <p class="ant-upload-hint">
              文件的上传格式为{{outFileType +"。"}}
            </p>
          </a-upload-dragger>
        </a-form-item>

        <!--      <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="审批结果">-->
        <!--        <a-switch-->
        <!--          checked-children="同意"-->
        <!--          un-checked-children="不同意"-->
        <!--          default-checked-->
        <!--          v-model="opinion.flag"-->
        <!--        />-->
        <!--      </a-form-item>-->
      </a-form>
      <template slot="footer">
        <a-button @click="handleCancel">返回</a-button>
        <a-button @click="handleOk" type="primary">提交</a-button>
        <!--        <a-popconfirm title="确定回退吗?" @confirm="() => handleBack()">-->
        <!--          <a-button v-if="opinionList && opinionList.length > 0" type="danger">回退</a-button>-->
        <a-button type="danger" @click="handleBack()" v-if="backButtonShow">退回</a-button>
        <!--        </a-popconfirm>-->
      </template>
    </a-modal>
    <a-modal
      title="回退列表"
      :width="500"
      :visible="backVisible"
      cancelText="关闭"
      @cancel="BackHandleCancel"
      wrapClassName="ant-modal-cust-warp"
      style="top:5%;height: 85%;overflow-y: hidden">
      <span slot="closeIcon">
          <a-icon type="close-circle"/>
      </span>
      <div>
        <a-checkbox-group @change="backCheck" v-if="checkboxShow">
          <a-row v-for="item in taskInfos">
            <a-col :span="24">
              <a-checkbox :value="item.id">
                {{item.name}}
              </a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </div>
      <template slot="footer">
        <a-button @click="backCheckOk" type="primary">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
  import pick from 'lodash.pick'
  // import { getProcessDetails, getTaskOpinions, completeTask } from '@/api/activiti'
  import {
    getProcessDetails,
    getTaskOpinions,
    completeTask,
    backTask,
    updateProcessStatus,
    loadTaskFileType,
    getLoadTaskFiles,
    isNotGateway,
    loadDescription,
    loadStart,
    loadEnd,
    loadDateDiff,
    loadTimeStatus,
    getLoadBackButton
  } from '@/api/activiti'


  export default {
    name: 'TaskModal',
    components: {},
    data() {
      return {
        //回退节点
        taskInfos: [],
        backTaskIds: [],
        checkboxShow: false,
        nodeType: "",
        backButtonShow: true,

        title: '任务执行',
        visible: false,
        backVisible: false,
        opinion: {
          taskId: '',
          opinion: '',
          flag: true
        },
        process: {},
        currentTask: {},
        fileAttachments: false,
        activityTask: {},
        opinionList: [],
        opinionColumns: [
          {
            title: '审批用户',
            align: 'center',
            dataIndex: 'userName'
          },
          {
            title: '审批时间',
            align: 'center',
            dataIndex: 'createTime'
          },
          {
            title: '审批意见',
            align: 'center',
            dataIndex: 'opinion'
          },
          {
            title: '审批结果',
            align: 'center',
            dataIndex: 'flag'
          }
        ],
        labelCol: {
          xs: {span: 24},
          sm: {span: 5}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 16}
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules: {
          opinion: {
            rules: [{min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}]
          }
        },
        outFileType: '',
        processInstanceId: '',
        description: '',
        userId: '',
        userName: '',
        startTime: '',
        endTime: '',
        dateDiff: '',
        timeStatus: '',
        fileList: []
      }
    },
    computed: {
      uploadAction() {
        return window._CONFIG['domianURL'] + '/sys/common/upload'
      },
      urlDownload() {
        return window._CONFIG['domianURL'] + '/sys/common/download/'
      }
    },
    filters: {
      fileName(link) {
        if (!link) {
          return ''
        }
        if (link.indexOf('/') < 0) {
          return link
        }
        let file = link.substr(link.lastIndexOf('/') + 1)
        let extIndex = file.lastIndexOf('.')
        return file.substring(0, extIndex - 14) + file.substr(extIndex)
      }
    },
    created() {
    },
    methods: {
      backCheck(checkedValues) {
        console.log('checked = ', checkedValues);
        this.backTaskIds = checkedValues
      },
      backCheckOk() {
        this.handleBack(1)
      },
      edit(record) {
        this.processInstanceId = record.processInstanceId
        this.form.resetFields()
        this.opinion.taskId = record.id
        //todo
        this.loadBackButton(record.processInstanceId, record.id)
        this.loadProcessDetails(record.id)
        this.loadOptionList(record.processInstanceId, record.id)
        this.loadTaskFileType(record.processInstanceId, record.id)
        this.loadTaskFile(record.processInstanceId, record.id)

        /*---新增----*/
        this.initDescription(record.processInstanceId)
        this.initStart(record.processInstanceId)
        this.initEnd(record.processInstanceId)
        this.initDateDiff(record.processInstanceId)
        this.loadTimeStatus(record.processInstanceId)

        this.visible = true
      },
      loadBackButton(processId, taskId) {
        let that = this
        getLoadBackButton(processId, taskId).then(res => {
          if (res.result == "StartEvent") {
            that.backButtonShow = false
          }
        })
      },
      loadOptionList(processId, taskId) {
        let vm = this
        getTaskOpinions(processId, taskId).then(res => {
          if (res.success && res.result && res.result.length > 0) vm.opinionList = [].concat(res.result)
        })
      },
      loadProcessDetails(processId) {
        let vm = this
        getProcessDetails(processId).then(res => {
          vm.process = Object.assign({}, res.result)
        })
      },
      //获取上传文件格式
      loadTaskFileType(processId, taskId) {
        let vm = this
        loadTaskFileType(processId, taskId).then(res => {
            vm.outFileType = res.result
          }
        )
      },
      //加载上个节点文件
      loadTaskFile(processId, taskId) {
        let that = this
        getLoadTaskFiles(processId, taskId).then(res => {
          console.log(res)
          that.currentTask = {}
          that.currentTask.attachments = res.result
          if (res.result.length > 0) {
            that.fileAttachments = true
          }
        })
      },

      //获取节点描述
      initDescription(processId) {
        let vm = this
        loadDescription(processId).then(res => {
            vm.description = res.result
            console.log("dsd:" + vm.description)
          }
        )
      },
      //获取开始时间
      initStart(processId) {
        let vm = this
        loadStart(processId).then(res => {
            vm.startTime = res.result
            console.log("dsd:" + vm.startTime)
          }
        )
      },
      //获取结束时间
      initEnd(processId) {
        let vm = this
        loadEnd(processId).then(res => {
            vm.endTime = res.result
            console.log("dsd:" + vm.endTime)
          }
        )
      },
      //获取执行天数
      initDateDiff(processId) {
        let vm = this
        loadDateDiff(processId).then(res => {
            vm.dateDiff = res.result
            console.log("dsd:" + vm.dateDiff)
          }
        )
      },
      //获取时间状态
      loadTimeStatus(processId) {
        let vm = this
        loadTimeStatus(processId).then(res => {
            console.log("dsd:" + res.result)
            if (res.result == 0) {
              vm.timeStatus = "正常范围";
            } else {
              vm.timeStatus = "时间超时";
            }

          }
        )
      },


      updateStatus() {
        updateProcessStatus(this.process.id)
      },
      close() {
        this.$emit('close')
        this.visible = false

      },
      updateTask() {
        return this.$refs.taskView.updateTask(this.opinion)
      },
      handleOk() {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {

          if (!err) {
            that.confirmLoading = true
            console.log(that.process)
            that.opinion = Object.assign(that.opinion, values, {attachments: that.activityTask.attachments},
              {attachmentsName: that.activityTask.attachmentsName},
              {processDefinitionId: that.process.processDefinitionId}, {processInstanceId: that.processInstanceId})
            completeTask(that.opinion).then(res => {
              if (res.success) {
                // that.updateStatus()
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
              that.confirmLoading = false
              that.close()
            })
          }
        })
      },
      handleCancel() {
        this.backTaskIds = []
        this.close()
      },
      BackHandleCancel() {
        this.backVisible = false
        this.backTaskIds = []
        this.checkboxShow = false
      },
      handleBack(num) {
        const that = this
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            that.opinion = Object.assign(that.opinion, values, {attachments: that.activityTask.attachments},
              {attachmentsName: that.activityTask.attachmentsName},
              {processDefinitionId: that.process.processDefinitionId}, {processInstanceId: that.processInstanceId},
              {backTaskIds: that.backTaskIds}, {taskInfos: that.taskInfos}, {nodeType: that.nodeType})
            if (num == 1) {
              backTask(that.opinion).then(res => {
                if (res.success) {
                  that.updateStatus()
                  that.$message.success(res.message)
                  that.$emit('ok')
                  that.backVisible = false
                } else {
                  that.$message.warning(res.message)
                }
                that.confirmLoading = false
                that.close()
              })
            } else {
              //todo
              isNotGateway(that.opinion).then(res => {
                if (res.nodeType == "Gateway") {
                  that.backVisible = true
                  that.taskInfos = res.result
                  that.nodeType = res.nodeType;
                } else if (res.nodeType == "Activity") {
                  that.backVisible = true
                  that.taskInfos = res.result
                  that.nodeType = res.nodeType;
                }
              })
              that.checkboxShow = true
            }
          }
        })
      },
      handleChange(info) {
        const status = info.file.status;
        if (status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (status === 'done') {
          this.$message.success(`${info.file.name} file uploaded successfully.`);
        } else if (status === 'error') {
          this.$message.error(`${info.file.name} file upload failed.`);
        }
      },
      uploadChanged(info) {
        console.log('--文件列表改变--')
        let fileList = info.fileList
        if (info.file.status === 'done') {
          let array = new Array()
          let fileNameArray = new Array();
          if (info.file.response.success) {
            fileList = fileList.map(file => {
              if (file.response) {
                file.url = this.urlDownload + file.response.message
                array.push(file.url)
                file.name = file.name
                fileNameArray.push(file.name)
              }
              return file
            })
          }
          this.activityTask.attachments = array.toString()
          this.activityTask.attachmentsName = fileNameArray.toString()
          this.$message.success(`${info.file.name} 上传成功!`)
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`)
        } else if (info.file.status === 'removed') {
          console.log(info.file + ' --- removed')
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          console.log(info.file + ' --- path changed')
        }
      },
      beforeUpload(file) {
        let filename = file.name
        let index1 = filename.lastIndexOf(".")
        let index2 = filename.length
        let type = filename.substring(index1, index2)
        if (this.outFileType.indexOf(type) == -1) {
          this.$message.error("非法格式文件")
          return false
        }
      },
    }
  }
</script>

<style scoped>
  /*@import '~@assets/less/common.less';*/
</style>